package com.huatai.datacenter.utils;

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;

/**
 * @author gusiyi
 * @version 1.0
 * @className AESUtils
 * @description 描述：对称加密工具类
 * @date 2023/6/14 16:29
 */
public class EncryptionUtils {

	private EncryptionUtils(){}

	private static final String AES_ALGORITHM = "AES";
	private static final String DES_ALGORITHM = "DES";

	public static String encrypt(String data, String key, String algorithm) throws NoSuchAlgorithmException,
		NoSuchPaddingException, InvalidKeyException, InvalidKeySpecException, IllegalBlockSizeException,
		BadPaddingException {
		SecretKey secretKey;
		if (algorithm.equals(AES_ALGORITHM)) {
			secretKey = new SecretKeySpec(Base64.getDecoder().decode(key), AES_ALGORITHM);
		} else if (algorithm.equals(DES_ALGORITHM)) {
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES_ALGORITHM);
			DESKeySpec desKeySpec = new DESKeySpec(Base64.getDecoder().decode(key));
			secretKey = keyFactory.generateSecret(desKeySpec);
		} else {
			throw new IllegalArgumentException("Unsupported algorithm: " + algorithm);
		}

		Cipher cipher = Cipher.getInstance(algorithm);
		cipher.init(Cipher.ENCRYPT_MODE, secretKey);
		byte[] encryptedBytes = cipher.doFinal(data.getBytes());
		return Base64.getEncoder().encodeToString(encryptedBytes);
	}

	public static String decrypt(String encryptedData, String key, String algorithm) throws NoSuchAlgorithmException,
		NoSuchPaddingException, InvalidKeyException, InvalidKeySpecException, IllegalBlockSizeException,
		BadPaddingException {
		SecretKey secretKey;
		if (algorithm.equals(AES_ALGORITHM)) {
			secretKey = new SecretKeySpec(Base64.getDecoder().decode(key), AES_ALGORITHM);
		} else if (algorithm.equals(DES_ALGORITHM)) {
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES_ALGORITHM);
			DESKeySpec desKeySpec = new DESKeySpec(Base64.getDecoder().decode(key));
			secretKey = keyFactory.generateSecret(desKeySpec);
		} else {
			throw new IllegalArgumentException("Unsupported algorithm: " + algorithm);
		}

		Cipher cipher = Cipher.getInstance(algorithm);
		cipher.init(Cipher.DECRYPT_MODE, secretKey);
		byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
		return new String(decryptedBytes);
	}
}
